# coding: utf8
import sys
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex

from my_crypto.__key__ import crypt_key


class prpcrypt():
    def __init__(self, key_16):
        self.key = key_16
        self.mode = AES.MODE_CBC

    # 加密函数
    # 加密文本必须为16的倍数，同时自动补足
    def encrypt_(self, text):
        cryptor = AES.new(self.key, self.mode, self.key)
        # 这里密钥key 长度必须为16（AES-128）、24（AES-192）、或32（AES-256）Bytes 长度.目前AES-128足够用
        length = 16
        count = len(text)
        add = length - (count % length)
        text = text + ('\0' * add)
        self.ciphertext = cryptor.encrypt(text)
        # 因为AES加密时候得到的字符串不一定是ascii字符集的，输出到终端或者保存时候可能存在问题
        # 所以这里统一把加密后的字符串转化为16进制字符串
        return b2a_hex(self.ciphertext)

    # 解密后，去掉补足的空格用strip() 去掉
    def decrypt_(self, text):
        cryptor = AES.new(self.key, self.mode, self.key)
        plain_text = cryptor.decrypt(a2b_hex(text))
        return plain_text.rstrip(b'\0')


Prpcrypt = prpcrypt(crypt_key)


# 加密字符串，并返回字符串形式密文
def encrypt(text_str):
    b_enc = Prpcrypt.encrypt_(text_str)
    enc = str(b_enc).split('\'')[1]

    # print(enc)
    return enc


# 解密，传入加密函数的返回值
def decrypt(encrypt_text):
    # 传入字符串
    b_dec = Prpcrypt.decrypt_(encrypt_text)
    dec = str(b_dec).split('\'')[1]

    # print(dec)
    return dec


# a = encrypt('asdasdaqasd2 gd feewf35rge5g456e4h324fhfgdfsd')
# b = decrypt(a)
# print(a)
# print(b)

# def aaa(username=None, password=None, aaaa=None, bbb=None):
#     # a = {'username': username, 'password': password, 'aaa': aaaa, 'bbb': bbb}
#     a = [username, password, aaaa, bbb]
#
#     # d = {'username': 'sun', 'password': '123', 'aaa': 'AAA', 'bbb': 'BBB'}
#     b = ['111', '222', '333', '444']
#     # data = []
#
#     # for key, values in d.items():
#     #     data.append(values)
#     #     print(data)
#
#     for i in range(len(a)):
#         if a[i]:
#             a[i] = b[i]
#     print(a)


# username = 'SUU'
# aaa(username=username, password=True)

